package org.example.controller;

import com.alibaba.fastjson.JSON;
import lombok.Data;

/**
 * @author Aaron
 * @since 2021/9/6 14:03
 * <p>描述：</p>
 */
@Data
public class CommonResponse<T> {

    private static final String FILE_STRING = "{}";
    private static final String FILE_FORMAT = "\\{}";

    /**
     * 返回码
     */
    private String code;
    /**
     * 返回提示信息
     */
    private String msg;
    /**
     * 返回数据
     */
    private T data;

    public static <T> CommonResponse<T> success(String msg) {
        CommonResponse<T> resp = new CommonResponse<>();
        resp.setCode("SUCCESS");
        resp.setMsg(msg);
        return resp;
    }

    public static <T> CommonResponse<T> success(T data, String msg) {
        CommonResponse<T> resp = new CommonResponse<>();
        resp.setCode("SUCCESS");
        resp.setData(data);
        resp.setMsg(msg);
        return resp;
    }

    public static <T> CommonResponse<T> error(String msg) {
        CommonResponse<T> resp = new CommonResponse<>();
        resp.setMsg(msg);
        resp.setCode("FAIL");
        return resp;
    }

    public static <T> CommonResponse<T> error(String msg, Object... args) {
        CommonResponse<T> resp = new CommonResponse<>();
        resp.setCode("FAIL");

        if (args == null) {
            if (!msg.contains(FILE_STRING)) {
                resp.setMsg(msg);
                return resp;
            }
            resp.setMsg(msg.replaceFirst(FILE_FORMAT, "null"));
            return resp;
        }

        StringBuilder stringBuilder = new StringBuilder(msg);
        for (Object arg : args) {
            if (arg instanceof Throwable) {
                Throwable throwable = (Throwable) arg;
                stringBuilder.append(throwable.toString()).append("\n");
                StackTraceElement[] stackTrace = throwable.getStackTrace();
                for (StackTraceElement stackTraceElement : stackTrace) {
                    stringBuilder.append(stackTraceElement).append("\n");
                }
                continue;
            }
            stringBuilder = new StringBuilder(stringBuilder.toString().replaceFirst(
                    FILE_FORMAT, arg == null ? "null" : arg.toString()));
        }

        resp.setMsg(stringBuilder.toString());
        return resp;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

}
